import { provide } from 'vue'
import type { InjectionKey } from 'vue'

import { ElMessage } from 'element-plus'
import { IMsg } from '@/components/form'

type TMessage = 'success' | 'info' | 'warning' | 'error'
type TTips = string

type TSendAction = (msg: IMsg) => void

export const elMessage = (type: TMessage = 'success', tips: TTips) => {
  ElMessage({
    type: type,
    message: tips || 'System Error',
    grouping: false
  })
}


// 函数的InjectionKey
export const sendMsgKey: InjectionKey<TSendAction> = Symbol('')

export class useAction {
  onMsgAction: any
  constructor(onMsgAction: any) {
    this.onMsgAction = onMsgAction
    provide(sendMsgKey, this.sendMsg)
  }

  sendMsg: TSendAction = (msg) => {
    try {
      this.onMsgAction[msg.action](msg.data)
    } catch(err) {
      elMessage('error', `页面中的onMsgAction中不存在方法：${msg.action}`)
    }
  }
}
